function toStyleList(styles, selector) {
    const entries = Object.entries(styles);
    const attrEntries = entries.filter(([, value]) => typeof value !== "object");
    const currentStyle = attrEntries.length
        ? `${selector} { ${attrEntries.map(([key, value]) => `${key}: ${value}`).join("; ")} }`
        : null;

    const subEntries = entries.filter(([, value]) => typeof value === "object")
        .flatMap(([key, value]) => toStyleList(value, mergeKey(selector, key)));

    if (currentStyle) {
        subEntries.unshift(currentStyle);
    }
    return subEntries;
}

function mergeKey(parent, key) {
    if (!parent) { return key; }

    if (key.startsWith("&")) {
        return `${parent}${key.substring(1)}`;
    }

    return `${parent} ${key}`;
}

export function toStyleString(styles) {
    return toStyleList(styles).join("\n");
}
